<template>
  <div class="churn-forecast">
    <div class="toolbar">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/forecast' }">智能预测</el-breadcrumb-item>
        <el-breadcrumb-item>客户流失预测</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="toolbar-actions">
        <el-button type="primary" @click="handleForecast">
          <el-icon><MagicStick /></el-icon>
          开始预测
        </el-button>
        <el-button type="danger" @click="handleIntervention">
          <el-icon><Warning /></el-icon>
          流失干预
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>
          导出报告
        </el-button>
      </div>
    </div>

    <!-- 流失概览 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="overview-item">
            <div class="overview-icon" style="background: linear-gradient(135deg, #f56c6c 0%, #ff9a9e 100%)">
              <el-icon :size="30"><WarningFilled /></el-icon>
            </div>
            <div class="overview-info">
              <div class="overview-value">{{ churnData.highRisk }}</div>
              <div class="overview-label">高风险客户</div>
              <div class="overview-trend up">
                <el-icon><Top /></el-icon> +15%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="overview-item">
            <div class="overview-icon" style="background: linear-gradient(135deg, #e6a23c 0%, #feca57 100%)">
              <el-icon :size="30"><Warning /></el-icon>
            </div>
            <div class="overview-info">
              <div class="overview-value">{{ churnData.mediumRisk }}</div>
              <div class="overview-label">中风险客户</div>
              <div class="overview-trend up">
                <el-icon><Top /></el-icon> +8%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="overview-item">
            <div class="overview-icon" style="background: linear-gradient(135deg, #67c23a 0%, #95de64 100%)">
              <el-icon :size="30"><CircleCheck /></el-icon>
            </div>
            <div class="overview-info">
              <div class="overview-value">{{ churnData.lowRisk }}</div>
              <div class="overview-label">低风险客户</div>
              <div class="overview-trend down">
                <el-icon><Bottom /></el-icon> -3%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="overview-item">
            <div class="overview-icon" style="background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%)">
              <el-icon :size="30"><User /></el-icon>
            </div>
            <div class="overview-info">
              <div class="overview-value">{{ churnData.churnRate }}%</div>
              <div class="overview-label">预测流失率</div>
              <div class="overview-trend up">
                <el-icon><Top /></el-icon> +2.3%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 流失趋势预测 -->
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span><el-icon><TrendCharts /></el-icon> 客户流失趋势预测</span>
            </div>
          </template>
          <div ref="churnTrendChartRef" style="height: 400px"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <span><el-icon><PieChart /></el-icon> 流失风险分布</span>
          </template>
          <div ref="riskDistChartRef" style="height: 400px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 高风险客户列表 -->
    <el-card shadow="hover" style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span><el-icon><User /></el-icon> 高风险客户列表</span>
          <el-input
            v-model="searchKeyword"
            placeholder="搜索客户"
            style="width: 200px"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </template>
      <el-table :data="highRiskCustomers" stripe style="width: 100%">
        <el-table-column type="index" label="#" width="60" />
        <el-table-column prop="customerName" label="客户名称" width="150" />
        <el-table-column prop="level" label="客户等级" width="100">
          <template #default="{ row }">
            <el-tag :type="getLevelType(row.level)">{{ row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="churnRisk" label="流失风险" width="120">
          <template #default="{ row }">
            <el-progress :percentage="row.churnRisk" :color="getChurnColor(row.churnRisk)" />
          </template>
        </el-table-column>
        <el-table-column prop="lastPurchase" label="最后消费" width="120" />
        <el-table-column prop="totalAmount" label="消费总额" width="120" />
        <el-table-column prop="purchaseFreq" label="消费频次" width="100" />
        <el-table-column prop="riskReason" label="流失原因" min-width="200" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleViewCustomer(row)">
              <el-icon><View /></el-icon>详情
            </el-button>
            <el-button link type="warning" @click="handleIntervene(row)">
              <el-icon><Phone /></el-icon>干预
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 流失原因分析 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <span><el-icon><DataAnalysis /></el-icon> 流失原因分析</span>
          </template>
          <div ref="reasonChartRef" style="height: 300px"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <span><el-icon><Opportunity /></el-icon> 挽回措施建议</span>
          </template>
          <el-timeline style="margin-top: 20px">
            <el-timeline-item
              v-for="(suggestion, index) in retentionSuggestions"
              :key="index"
              :color="suggestion.color"
              :timestamp="suggestion.priority"
            >
              <h4>{{ suggestion.title }}</h4>
              <p>{{ suggestion.content }}</p>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

const searchKeyword = ref('')

const churnData = ref({
  highRisk: 156,
  mediumRisk: 284,
  lowRisk: 1456,
  churnRate: 8.2
})

const highRiskCustomers = ref([
  {
    id: 1,
    customerName: '张三',
    level: 'VIP',
    churnRisk: 85,
    lastPurchase: '90天前',
    totalAmount: '¥58,600',
    purchaseFreq: 23,
    riskReason: '购买频次明显下降，长期未消费'
  },
  {
    id: 2,
    customerName: '李四',
    level: '高级会员',
    churnRisk: 78,
    lastPurchase: '75天前',
    totalAmount: '¥42,300',
    purchaseFreq: 18,
    riskReason: '客单价持续下降，活跃度降低'
  },
  {
    id: 3,
    customerName: '王五',
    level: 'VIP',
    churnRisk: 92,
    lastPurchase: '120天前',
    totalAmount: '¥95,800',
    purchaseFreq: 45,
    riskReason: '投诉未及时处理，满意度下降'
  },
  {
    id: 4,
    customerName: '赵六',
    level: '高级会员',
    churnRisk: 73,
    lastPurchase: '65天前',
    totalAmount: '¥36,500',
    purchaseFreq: 15,
    riskReason: '竞品吸引，价格敏感'
  }
])

const retentionSuggestions = ref([
  {
    title: '个性化优惠券',
    content: '向高风险客户发送专属优惠券，刺激复购',
    priority: '高优先级',
    color: '#f56c6c'
  },
  {
    title: '专人回访',
    content: '安排客服人员主动回访，了解需求和问题',
    priority: '高优先级',
    color: '#e6a23c'
  },
  {
    title: '会员权益升级',
    content: '提供临时会员等级升级，增强归属感',
    priority: '中优先级',
    color: '#409eff'
  },
  {
    title: '产品推荐',
    content: '基于历史购买行为，推荐相关产品',
    priority: '中优先级',
    color: '#67c23a'
  }
])

const churnTrendChartRef = ref(null)
const riskDistChartRef = ref(null)
const reasonChartRef = ref(null)

const handleForecast = () => {
  ElMessage.success('正在执行客户流失预测分析...')
}

const handleIntervention = () => {
  ElMessage.success('正在启动批量干预方案...')
}

const handleExport = () => {
  ElMessage.success('报告导出成功')
}

const handleViewCustomer = (row) => {
  ElMessage.info(`查看客户详情：${row.customerName}`)
}

const handleIntervene = (row) => {
  ElMessage.success(`正在为客户"${row.customerName}"启动挽回方案...`)
}

const getLevelType = (level) => {
  const typeMap = { 'VIP': 'danger', '高级会员': 'warning', '普通会员': 'info' }
  return typeMap[level] || ''
}

const getChurnColor = (churnRisk) => {
  if (churnRisk >= 80) return '#f56c6c'
  if (churnRisk >= 60) return '#e6a23c'
  return '#67c23a'
}

const initCharts = () => {
  if (churnTrendChartRef.value) {
    const chart = echarts.init(churnTrendChartRef.value)
    const option = {
      tooltip: { trigger: 'axis' },
      legend: { data: ['实际流失率', '预测流失率'] },
      xAxis: { type: 'category', data: ['1月', '2月', '3月', '4月', '5月', '6月'] },
      yAxis: { type: 'value', name: '流失率(%)' },
      series: [
        {
          name: '实际流失率',
          type: 'line',
          data: [5.8, 6.2, 6.5, 7.1, null, null],
          itemStyle: { color: '#409eff' }
        },
        {
          name: '预测流失率',
          type: 'line',
          data: [null, null, null, 7.1, 7.8, 8.2],
          itemStyle: { color: '#f56c6c' },
          lineStyle: { type: 'dashed' }
        }
      ]
    }
    chart.setOption(option)
  }

  if (riskDistChartRef.value) {
    const chart = echarts.init(riskDistChartRef.value)
    const option = {
      tooltip: { trigger: 'item' },
      series: [
        {
          name: '风险分布',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 156, name: '高风险', itemStyle: { color: '#f56c6c' } },
            { value: 284, name: '中风险', itemStyle: { color: '#e6a23c' } },
            { value: 1456, name: '低风险', itemStyle: { color: '#67c23a' } }
          ]
        }
      ]
    }
    chart.setOption(option)
  }

  if (reasonChartRef.value) {
    const chart = echarts.init(reasonChartRef.value)
    const option = {
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
      xAxis: { type: 'value' },
      yAxis: {
        type: 'category',
        data: ['其他', '竞品吸引', '价格因素', '服务质量', '产品质量', '活跃度下降']
      },
      series: [
        {
          name: '原因占比',
          type: 'bar',
          data: [12, 18, 25, 28, 32, 45],
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#667eea' },
              { offset: 1, color: '#764ba2' }
            ])
          }
        }
      ]
    }
    chart.setOption(option)
  }
}

onMounted(() => {
  nextTick(() => {
    initCharts()
  })
})
</script>

<style scoped lang="scss">
@use './forecast-common.scss';
</style>

